
import React, { useState,useEffect } from 'react';
import { Button, Descriptions, Input, message, Spin, Select, DatePicker, InputNumber, Upload } from 'antd';
import { useNavigate } from 'react-router-dom';
import { AddGoods,getGoodsTypes} from '../../api/goods';
import "../../css/supplier.css";
const { TextArea } = Input;
const Add = () => {

    const navigate = useNavigate();
    const [name, setName] = useState('');
    const [type, setType] = useState('');
    const [price, setPrice] = useState('');
    const [specs, setSpecs] = useState('');
    const [birthday, setBirthday] = useState('');
    const [expiryday, setExpiryday] = useState('');
    const [explain, setExplain] = useState('');
    const [spinning, setSpinning] = React.useState(false);//加载中
    const  [types,setTypes]=useState([]);
    const data = async () => {
        await getGoodsTypes({
        }).then((res) => {
            if (res.result === 0) {
                setTypes(res.data.data);
            }
        })
    }
    const options = types.map((item) => ({
        value: item.id,
        label: item.name,
    }));
    useEffect(() => {
        data();
    }, []); // 空数组意味着这个effect只在组件挂载和卸载时运行  


     


    const add = async () => {
        setSpinning(true);
        await AddGoods({
            name: name,
            type: type,
            price: price,
            specs: specs,
            birthday: birthday,
            expiryday: expiryday,
            explain: explain,
            photo: imageUrl
        }).then((res) => {
            if (res.result === 0) {
                setSpinning(false);
                message.success('添加成功', 1.5);
                navigate(`/goods`);
            }
        })
    }
    const handleNameChange = (e) => {
        setName(e.target.value);
    };
    const handleChangeType = (value) => {
        setType(value)
    };
    const handlePriceChange = (value) => {
        setPrice(value);
    };
    const handleSpecsChange = (e) => {
        setSpecs(e.target.value);
    };
    const handleBirthdayChange = (value) => {
        setBirthday(value);
    };
    const handleExpirydayChange = (value) => {
        setExpiryday(value);
    };
    const handleExplainChange = (e) => {
        setExplain(e.target.value);
    };
    const [imageUrl, setImageUrl] = useState();
    const handleChange = (info) => {
        if (info.file.status === 'uploading') {
            return;
        }
        if (info.file.status === 'done') {
            getBase64(info.file.originFileObj, (url) => {
                setImageUrl(info.fileList[0].response);
            });
        }
    };
    const getBase64 = (img, callback) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    };

    const beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('您只能上传JPG/PNG文件!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('图像必须小于2MB!');
        }
        return isJpgOrPng && isLt2M;
    };

    const items = [
        {
            key: '1',
            label: '商品名称',
            children: <Input value={name} onChange={handleNameChange} />,
            span: 1.5,
        },
        {
            key: '2',
            label: '类型',
            children: (
                <>
                     <Select defaultValue={types}
                    style={{ width: "100%" }}
                    placeholder="请选择商品类型"
                    onChange={handleChangeType}
                    options={options} />
                </>
            ),
            span: 1.5
        },
        {
            key: '3',
            label: '价格',
            children: <InputNumber value={price} min={1} max={10} onChange={handlePriceChange} defaultValue={0} style={{
                width: '100%',
            }} />,
            span: 1.5,
        },
        {
            key: '4',
            label: '规格',
            children: <Input value={specs} onChange={handleSpecsChange} />,
            span: 1.5,
        },
        {
            key: '5',
            label: '生产日期',
            children: <DatePicker value={birthday} placeholder="选择生产日期" onChange={handleBirthdayChange} style={{
                width: '100%',
            }} />,
            span: 1.5,
        },
        {
            key: '6',
            label: '保质期(天)',
            children: <InputNumber value={expiryday} min={1} max={10} defaultValue={0} onChange={handleExpirydayChange} style={{
                width: '100%',
            }} />,
            span: 1.5,
        },
        {
            key: '7',
            label: '描述',
            children:
                <TextArea rows={3} maxLength={6} value={explain} onChange={handleExplainChange} />,
            span: 3,
        },
        {
            key: '8',
            label: '封面',
            children: <>
                <Upload
                    name="avatar"
                    listType="picture-card"
                    className="avatar-uploader"
                    showUploadList={false}
                    action="https://sapi.jiangdaye.cn/api/Resource/Upload"
                    beforeUpload={beforeUpload}
                    onChange={handleChange}
                >
                    {imageUrl ? (
                        <img
                            src={imageUrl}
                            alt="avatar"
                            style={{
                                width: '100%',
                            }}
                        />
                    ) : (
                        '点击选择图片'
                    )}
                </Upload>
            </>
            ,
            span: 3,
        },
        {
            key: '9',
            label: '操作',
            children: <Button type="primary" onClick={() => add()} >新增</Button>,
            span: 3,
        },

    ];
    return (
        <div className='exam-container'>
            <div className="container">
                <div className="content">
                    <Descriptions title="新增商品" layout="vertical" bordered items={items} />
                </div>
            </div>

            <Spin spinning={spinning} tip="Loading" fullscreen />
        </div>
    );
};


export default Add;